﻿using System;
using DirectShowLib;
using MediaFoundation.EVR;

namespace MediaPlayer.Renderers
{
    public class VMR7 : Basic, IDisposable
    {
        public VMR7(IntPtr handle)
            : base(handle)
        {
            this.filter = (IBaseFilter)new VideoMixingRenderer();

            Player.Graph.AddFilter(this.filter, "Video Mixing Renderer");

            IVMRFilterConfig filterConfig = (IVMRFilterConfig)this.filter;

            int hr = filterConfig.SetNumberOfStreams(1);
            DsError.ThrowExceptionForHR(hr);

            // Change VMR7 mode to Windowless
            hr = filterConfig.SetRenderingMode(VMRMode.Windowless);
            DsError.ThrowExceptionForHR(hr);

            this.Control = (IVMRWindowlessControl)this.filter;

            // Set rendering window
            hr = this.Control.SetVideoClippingWindow(this.handle);
            DsError.ThrowExceptionForHR(hr);
        }

        override public void SetVideoPosition(MFVideoNormalizedRect src, DsRect dst)
        {
            this.Control.SetVideoPosition(null, dst);
        }

        override public void DisplayModeChanged()
        {
            this.Control.DisplayModeChanged();
        }

        override public void Repaint(IntPtr hdc)
        {
            int hr = this.Control.RepaintVideo(this.handle, hdc);
            DsError.ThrowExceptionForHR(hr);
        }

        ~VMR7()
        {
            try
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            finally
            {
                base.Dispose();
            }
        }
    }
}
